<template>
  <div>
    <!--<el-row>{{routeName}}&#45;&#45;&#45;&#45; {{isLongStore}}</el-row>-->
    <!--新：订单信息 + 客户信息（与出库单详情的 共用同一组件）-->
    <OrderInfo :chOrderService="headerDetail" :routeName="routeName" :state="state"></OrderInfo>

    <!--客户信息）-->
    <UserInfo :chOrderConsigneeInfo="chOrderConsigneeInfo" v-if="headerDetail.orderType === 'STORAGEORDERTYPE01'"></UserInfo>
    <!--新版：商品信息（自定义商品 和标准商品 合在一起，用productType切换）-->
    <!--新版：未确认 和已确认 用state来切换显示: 不同的state+不同的商品类型不同： 展示的表单不同-->
    <Portlet title="商品信息"  style="position:relative;">
      <!--搜索表单-->
      <el-form ref="searchForm" class="el-form-s el-form-col" :model="search" label-position="left" v-if="state == 3">
        <el-row>
          <el-col :lg="5" :xl="5">
            <el-form-item prop="manufacturersName" >
              <el-input clearable placeholder="厂家名称" v-model="search.manufacturersName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :xl="5" :offset="1">
            <el-form-item prop="productName" >
              <el-input clearable placeholder="商品名称" v-model="search.productName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :xl="5" :offset="1">
            <el-form-item prop="packageName" >
              <el-input clearable placeholder="包件名称" v-model="search.packageName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :xl="5" :offset="1">
            <el-form-item >
              <!--<el-button type="primary" @click.prevent="searchFunc">搜索</el-button>-->
              <el-button type="primary" @click.prevent="reset">重置</el-button>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <!--表单-->
      <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="100px">
        <el-form-item label-width="0" prop="chOrderOutWarehousePackageList" :rules="[
                  {required: true, message: '商品信息必须', trigger: 'change', type: 'array'}
               ]">
          <el-table
            :data="model.chOrderOutWarehousePackageList | filterActive(this.search)"
            style="width:100%"
            border
            class="text-center"
          >
            <el-table-column
              align="center"
              min-width="150px"
              prop="manufacturersName"
              label="厂家名称"
            >
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="productNo"
              label="商品编号">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="productName"
              label="商品名称">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="bigClass"
              label="商品大类">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="middleClass"
              label="商品小类">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="80px"
              prop="standard"
              label="规格">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="120px"
              prop="packageCode"
              label="包件编号">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              min-width="150px"
              prop="packageName"
              align="center"
              label="包件名称">
            </el-table-column>

            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="100px"
              prop="packageOneVolume"
              label="单包件体积">
              <template slot-scope="scope">
                {{ scope.row.packageOneVolume | decimalNumFilter}}
              </template>
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="100px"
              prop="packageOneWeight"
              label="单包件重量">
            </el-table-column>
            <el-table-column
              v-if="productType == 2 || productType == 3"
              align="center"
              min-width="120px"
              prop="productNum"
              label="商品数量">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="115px"
              prop="packagePlanNum"
              label="包件计划出库">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="150px"
              v-if="state == 3"
              label="包件实际出库">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="'chOrderOutWarehousePackageList.' + scope.$index + '.realNum'" :rules="[
                          {required: true, message: '实际出库包件必须', trigger: 'change'}
                       ]">
                  <el-input v-model="scope.row.realNum" :min="0" :max="99999" label="描述文字"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              v-if="state == 4"
              prop="num"
              align="center"
              min-width="115px"
              label="包件实际出库">
            </el-table-column>
            <!--当未确认3 且为长期仓储时，可以修改库位  && isLongStore-->
            <el-table-column
              v-if="state == 3 && isLongStore"
              min-width="200px"
              align="center"
              label="分配库位">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="'chOrderOutWarehousePackageList.' + scope.$index + '.positionNum'" :rules="[
                          {required: true, message: '库位必须', trigger: 'change'}
                       ]">
                  <!--后端规定的：根据订单号orderId来查询 库位字典-->
                  <select-position v-model="scope.row.positionNum" :id="scope.row.orderId"></select-position>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isLongStore"
              align="center"
              min-width="120px"
              prop="positionName"
              label="分配库位">
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div style="position:absolute;left:140px;top:17px;font-size:14px;color:red">商品类型： {{getProductName(productType)}}</div>
      <div v-if="state == 3" style="position:absolute;right:26px;top:8px;font-size:14px;"><el-button type="primary" @click.prevent="submit">确认出库</el-button></div>
      <!--总的包件体积重量-->
      <el-row style="margin-top:15px;font-size:14px">
        <el-col :span="6">
          总包件：<span> {{totalPackage}} 件</span>
        </el-col>
        <el-col :span="6">
          总体积：<span> {{totalVolumes}} m³</span>
        </el-col>
        <el-col :span="6">
          总重量：<span> {{totalWeight}} kg</span>
        </el-col>
      </el-row>
    </Portlet>

  </div>
</template>

<script>
import {copy, dotData, alert} from '@/utils'
import OrderInfo from '@/views/oms/outputWarehouse/warehousingOrder/OrderInfo'
import UserInfo from '@/views/oms/outputWarehouse/warehousingOrder/UserInfo'
import SelectPosition from '@/views/oms/business/SelectPositionByEnter'
import {decimalNumFilter, unixTimestampFilter} from '@/filters'
import PackageTable from '@/views/oms/business/PackageTable'
import DBLike from '@/utils/DBLike'
export default {
  name: 'warehouseRecordOutShow',
  components: {
    UserInfo,
    OrderInfo,
    PackageTable,
    DBLike,
    SelectPosition
  },
  filters: {
    decimalNumFilter,
    unixTimestampFilter,
    filterActive: (arr, search) => {
      return new DBLike(arr).search(search)
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      state: this.$route.query.state,
      routeName: this.$route.name,
      headerDetail: {},
      chOrderConsigneeInfo: {},
      loading: false,
      model: { // 把整个表格 都看作是要提交的东东model
        chOrderOutWarehousePackageList: [
        ]
      },
      getDataTable: [], // 已确认的table展示信息
      params: {
        pageSize: 20,
        pageNum: 1
      },
      rules: {},
      search: {
        manufacturersName: '',
        productName: '',
        packageName: ''
      }
      // totalItem: 0
    }
  },
  created() {
    // 获取表头
    if (this.id) {
      this.$ajax.get('/ms-warehouse-order/outWarehose/findByOrderInfo', {outOrderId: this.id}).then(response => {
        // const success = dotData(response, 'success')
        if (response.success) {
          this.headerDetail = dotData(response, 'data')
          this.chOrderConsigneeInfo = dotData(response, 'data.chOrderConsigneeInfo')
          console.log('请求回来的头部信息', this.headerDetail)
        }
      })
    }
    // 获取包件
    this.httpGetPackage()
  },
  computed: {
    // 标准产品1，通用产品2==自定义产品3
    productType() {
      return dotData(this.headerDetail, 'productType') || 1 // 默认为标准产品
    },
    // 存储类型： 长期CARGOSOURCETYPE01、临时（快进快出）
    isLongStore() {
      let type = dotData(this.headerDetail, 'outTypeCode') || ''
      console.log('type', type)
      if (type === 'CARGOSOURCETYPE01') {
        return true
      }
      return false
    },
    // 总包件：总体积：总重量
    totalPackage() {
      let num = 0
      if (Array.isArray(this.model.chOrderOutWarehousePackageList)) {
        this.model.chOrderOutWarehousePackageList.forEach(v => {
          num += v.packagePlanNum
        })
      }
      return decimalNumFilter(num)
    },
    totalVolumes() {
      let num = 0
      if (Array.isArray(this.model.chOrderOutWarehousePackageList)) {
        this.model.chOrderOutWarehousePackageList.forEach(v => {
          num += v.volume
        })
      }
      return decimalNumFilter(num)
    },
    totalWeight() {
      let num = 0
      if (Array.isArray(this.model.chOrderOutWarehousePackageList)) {
        this.model.chOrderOutWarehousePackageList.forEach(v => {
          num += v.weight
        })
      }
      return decimalNumFilter(num)
    }
  },
  methods: {
    unixTimestampFilter,
    httpGetPackage() {
      // this.params.id = this.id
      return this.$ajax.get('/ms-warehouse-order/outWarehose/findByOutWarehouseInfo', {outOrderId: this.id}).then(response => {
        if (response.success) {
          this.totalItem = response.total
          this.model.chOrderOutWarehousePackageList = response.data
          this.getDataTable = response.data
          this.model.chOrderOutWarehousePackageList.forEach(v => { // 初始化新建字段 放进chOrderOutWarehousePackageList里面
            // 新建 实际包件数realNum: 默认为计划包件数
            this.$set(v, 'realNum', v.packageLastNum)
            // 分配库位，若返有库位id,回填之，否初始为空
            if (v.positionId) {
              this.$set(v, 'positionNum', v.positionId)
            } else {
              this.$set(v, 'positionNum', '')
            }
            // 加一个 rowId
            this.$set(v, 'RowId', v.id) // 新建 包件id字段，存该行的id
          })
          console.log('1111', this.model.chOrderOutWarehousePackageList)
        }
      })
    },
    searchFunc() {
      // this.params = merge(this.params, this.search)
      // this.httpGetPackage()
    },
    // reset 重置搜索框
    reset(searchForm) {
      this.$refs.searchForm.resetFields()
    },
    // 过滤出 商品类型
    getProductName(type) {
      if (type === 1) {
        return '标准产品'
      } else if (type === 2) {
        return '通用产品'
      } else if (type === 3) {
        return '自定义产品'
      }
      return ''
    },
    // 待确认的 求和
    getSum(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = '合计'
        } else {
          if (column.property === 'packageVolume' || column.property === 'num' || column.property === 'packagePlanNum') {
            let temp = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = decimalNumFilter(temp)
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let tempArr = []
        let data = copy(this.model, true)
        if (Array.isArray(data.chOrderOutWarehousePackageList)) {
          data.chOrderOutWarehousePackageList.forEach(v => {
            tempArr.push({
              id: v.RowId, // 换成后端字段名
              packageNum: v.realNum,
              packageLocationId: this.isLongStore ? v.positionNum : '' // 长期仓储才需提交库位id
            })
          })
        }
        data.chOrderOutWarehousePackageList = tempArr
        data.outOrderId = this.id
        let url = '/ms-warehouse-order/outWarehose/confirmOutBound'
        console.log('postData', data)
        this.$confirm('<p>确认货物都已出库完成？</p><p>系统将按照实际出库包件扣减库存</p>', '提示', {
          type: 'warning',
          center: true,
          dangerouslyUseHTMLString: true,
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            instance.confirmButtonLoading = false
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confrimButtonText = '出库中...'
              this.$ajax.post(url, data).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$confirm('已完成出库', '已出库', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/redirect/ss-oms/outputWarehouse/warehouse-confirm/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$message({
                      type: 'error',
                      message: `提交失败`
                    })
                  }, 500)
                }
              })
            } else { done() }
          }
        })
      })
    }
  }
}
</script>
